import _thread
import machine
import json
import app_config
import time

def wait_input_cmd(id):
    while True:
        try:
            inputcmd = input('please input cmd:')
            inputcmd_dict = json.loads(inputcmd)
            if isinstance(inputcmd_dict,dict):
                if 'lan' in inputcmd_dict and isinstance(inputcmd_dict['lan'],dict):
                    if "ip" and "subnet"  and "gateway" and "heartBeat" and "dns" in inputcmd_dict["lan"] :
                        app_config.write_cfg(inputcmd_dict)
                        time.sleep_ms(200)
                        machine.reset()
                    else:
                        print("some is None:%s"%inputcmd_dict)                      

                if 'mqtt_lte' in inputcmd_dict and isinstance(inputcmd_dict['mqtt_lte'],dict):
                    if "deviceCode" and "deviceSecret" and "deviceKey" and "serveraddr" and "serverport" and "qos1" in inputcmd_dict["mqtt_lte"]:
                        app_config.write_cfg({"serveraddr":inputcmd_dict["mqtt_lte"]["serveraddr"]})
                        app_config.write_cfg({"serverport":inputcmd_dict["mqtt_lte"]["serverport"]})
                        app_config.write_cfg({"qos1":inputcmd_dict["mqtt_lte"]["qos1"]})
                        app_config.write_cfg({"deviceCode":inputcmd_dict["mqtt_lte"]["deviceCode"]})
                        app_config.write_cfg({"deviceSecret":inputcmd_dict["mqtt_lte"]["deviceSecret"]})
                        app_config.write_cfg({"deviceKey":inputcmd_dict["mqtt_lte"]["deviceKey"]})
                        time.sleep_ms(200)
                        machine.reset()
                    else:
                        print("some is None:%s"%inputcmd_dict)

                if 'tcp' in inputcmd_dict and isinstance(inputcmd_dict['tcp'],dict):
                    if "host" and "port"  in inputcmd_dict["tcp"] :
                        app_config.write_cfg(inputcmd_dict)
                        time.sleep_ms(200)
                        machine.reset()
                    else:
                        print("some is None:%s"%inputcmd_dict)    
                if 'sensmodel' in inputcmd_dict:
                    app_config.write_cfg({"sensmodel":inputcmd_dict["sensmodel"]})

                if 'reporttime' in inputcmd_dict:
                    app_config.write_cfg({"reporttime":inputcmd_dict["reporttime"]})

            else:
                print("imput cmd is not a dict")
            
            pass
        except ValueError:
            '''other cmd process'''
            print('input cmd is:' + inputcmd)
            pass
        except KeyboardInterrupt:
            _thread.exit()

        finally:
            pass

def uart_thread():
    _thread.start_new_thread(wait_input_cmd,(4,))